package com.leectrl.controller;

import android.os.Environment;

import com.hdl.school.application.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class WebController {
    public static Object request(String url) throws IOException {
        if(url.equals("")||url.equals("/")){
            url="/index.html";
        }
        String path="www"+url;
        InputStream inputStream = MyApplication.myApplication.getAssets().open(path);
        if(inputStream==null){
            return null;
        }
        File respFile=copyFileFromAssets(inputStream,path);
        return respFile;
    }

    public static File copyFileFromAssets(InputStream is, String path) {
        try {
            File file = new File(Environment.getDataDirectory()+File.separator+path);
            if(file.exists()){
                file.delete();
            }
//            if(file.exists()){
//                return file;
//            }
            File dir=file.getParentFile();
            if(!dir.exists()){
                dir.mkdirs();
            }
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
